<?php namespace App\Core\Service\Services;

use DB;
use App\Core\Repository\Sorts\InputDragSort;

trait Sorter{
    
    public $sortConfig = [];
    
    public function initSorter($config = []){
        try {
            $this->sortConfig = $config;
            $this->fireEvent('sortBeforeAddSortHandle');
            $this->sortAddSortHandle($config);
		} catch (\Exception $ex) {
            throw $ex;
        }
    }
    
    public function applySort(){
        try {
            $this->fireEvent('sortBeforeSave');
            $this->sortSaveData();
            $this->fireEvent('sortAfterSave');
            return $this->success();
		} catch (\Exception $ex) {
            return $this->sysError($ex);
		}
    }
    
    protected function sortAddSortHandle(){
        $this->getRepository()->setSortHandle(new InputDragSort($this->sortConfig));
        return $this;
    }
    
    protected function sortSaveData(){
        DB::beginTransaction();
        try {
            $this->fireEvent('sortSaving');
            $this->getRepository()->applySort();
            $this->fireEvent('sortSaved');
            DB::commit();
		} catch (\Exception $ex) {
            DB::rollBack();
			throw $ex;
        }
    }
}